package com.lyhlmj.oop_client.Threads;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Utils.ExitUtil;
import com.lyhlmj.oop_client.Utils.Request;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;

public class GetPlayStatusTask extends Thread {
    private static Client client = Client.client;
    private Window owner;

    boolean quitFlag = false;  //终止标识符，为true时循环终止

    private JFrame frame;
    private Integer playId = 0;
    private String theStatus;
    private String chessResult;
    private String turn;  //回合
    private String color;  //当前用户的颜色
    private String[] players;  //参与对局的两个玩家的用户名

    private String winner = "";  //对局获胜者

    public GetPlayStatusTask(Window owner) {
        this.owner = owner;
    }

    //用来终止当前进程
    public void doStop() {
        quitFlag = true;
        System.out.println(" ** 关闭获取游戏状态的线程");
        this.interrupt(); // 让  sleep() 立即中止
        try {
            this.join(); // 等待本线程结束后再退出
        } catch (Exception e) {
        }
    }

    public void run() {
        while (!quitFlag) {
            try {
                sleep(200);  //每0.2s执行一次
            } catch (InterruptedException e) {
            }

            try {
                getPlayStatus();

                if (winner != null & !winner.equals("")) {
                    if (winner.equals(client.getUsername())) {
                        //弹出提示用户信息
                        JOptionPane.showMessageDialog(frame, "恭喜您获得本次对局的胜利！");
                    } else {
                        JOptionPane.showMessageDialog(frame, "失败是成功之母！期待您下次对局的精彩表现");
                    }

                    Thread.sleep(300); //系统休息0.3秒后，关闭当前线程在内的所有控制线程
                    //玩家获胜
                    ExitUtil.exitAfterWin(frame);
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;  //发送请求错误
            }

//            System.out.println(theStatus);
//            System.out.println(chessResult);
//            System.out.println(turn);
//            System.out.println(color);
//            System.out.println(playId);
        }
    }

    //用来获取当前用户的对局状态（正在比赛）和对局信息（棋子的数组）
    //返回执行结果是否正常
    private synchronized void getPlayStatus() {
        synchronized (client) {
            //向后台传送playId，如果值不为0则后续根据playId进行查找
            JSONObject jsonReq = Request.getJsonObject("getPlayStatus", "username", client.getUsername(), "playId", playId.toString());
            try {
                //向后端发送请求，并手动获取后端传入的参数（不使用回调函数，因为回调函数同一时间只能存在一个！）
                JSONObject jsonResp = client.send(jsonReq);
//                System.out.println(jsonResp);

                int status = jsonResp.optInt("status", -100);
                if (status != 0) {  //服务器处理出现问题
//                        JOptionPane.showMessageDialog(owner, reason);
//                    System.out.println("服务器处理错误！");
                    return;
                }
//              更新后端传入的信息
                JSONObject data = jsonResp.optJSONObject("data");
                //获取用户当前的对局号，便于用户获取后续信息
                playId = data.optInt("playId", 0);
                if (playId != 0) {
                    Client.client.setPlayId(playId);
                }

                theStatus = data.optString("status", "");
                chessResult = data.optString("chessResult", "");
                turn = data.optString("turn", "");
                color = data.optString("color", "");
                players = new String[2];
                players[0] = data.optString("player1", "");
                players[1] = data.optString("player2", "");

                Client.client.setPlayers(players);

                winner = data.optString("winner", "");  //获取获胜者，如果存在的话表示有一方获胜了

            } catch (Exception e) {
                System.out.println("对局信息接受失败！");
                e.printStackTrace();
            }
        }
    }

    ///////////////////////
    public String getTheStatus() {
        return theStatus;
    }

    public String getChessResult() {
        return chessResult;
    }

    public String getTurn() {
        return turn;
    }

    public String getColor() {
        return color;
    }

    public String[] getPlayers() {
        return players;
    }

    ///////////////////////
    public void setFrame(JFrame frame) {
        this.frame = frame;
    }
}
